package com.zclcs.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zclcs.mapper.RoleMapper;
import com.zclcs.mapper.RoleUserMapper;
import com.zclcs.model.DataRet;
import com.zclcs.model.Role;
import com.zclcs.model.RoleUser;
import com.zclcs.service.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private RoleUserMapper roleUserMapper;

	@Override
	public IPage<Role> selectRolePage(Role role) {
		if (role.getUuid() == null || "".equals(role.getUuid())) {
			role.setUuid("0");
		}
		Page<Role> page = new Page<>(role.getPage(), role.getLimit());
		return roleMapper.selectRolePage(page, role.getUuid(),
				new QueryWrapper<Role>()
						.like(role.getName() != null && !role.getName().equals(""), "name", role.getName()).or()
						.like(role.getDescription() != null && !role.getDescription().equals(""), "description",
								role.getDescription())
						.orderBy(role.getSort() != null, role.getSort().equals("asc"), "id"));
	}

	@Override
	public void insertRole(Role role) {
		roleMapper.insert(role);
	}

	@Override
	public DataRet<Object> deleteRole(List<String> ids) {
		if (roleMapper.selectIsAdmin(new QueryWrapper<Role>().in("r.id", ids)) > 0) {
			String[] adminUser = roleMapper.selectAdminRole(new QueryWrapper<Role>().in("r.id", ids));
			String jsonString = JSON.toJSONString(adminUser);
			return new DataRet<>(999, "请勿删除以下角色：" + jsonString);
		}
		int deleteBatchIds = roleMapper.deleteBatchIds(ids);
		return new DataRet<>("删除成功，删除的记录数：" + deleteBatchIds);
	}

	@Override
	public void updateRole(Role role) {
		roleMapper.updateById(role);
	}

	@Override
	public Boolean validRoleName(Role role) {
		Integer selectCount = roleMapper.selectCount(new QueryWrapper<Role>().eq("name", role.getName()));
		if (null != role.getId() && !"".equals(role.getId())) {
			Role role2 = roleMapper.selectOne(new QueryWrapper<Role>().eq("id", role.getId()));
			return (role.getName().equals(role2.getName())) ? true : (selectCount == 1) ? false : true;
		} else {
			return (selectCount == 1) ? false : true;
		}
	}

	@Override
	public void pickUpRoles(RoleUser roleUser) {
		roleUserMapper.insert(roleUser);
	}

	@Override
	public void putDownRoles(RoleUser roleUser) {
		roleUserMapper.delete(
				new QueryWrapper<RoleUser>().eq("role_id", roleUser.getRoleId()).eq("user_id", roleUser.getUserId()));
	}

}
